package cn.doctorpda.conference.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.doctorpda.conference.R;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.bean.checkmeeting.UserIcon;
import cn.doctorpda.conference.event.GetBitmap;
import cn.doctorpda.conference.event.GetLoginMessage;
import cn.doctorpda.conference.event.IsNew;
import cn.doctorpda.conference.localstore.ClientInfo;
import cn.doctorpda.conference.localstore.UserInfo;
import cn.doctorpda.conference.presenter.ChangeHeadPresenter;
import cn.doctorpda.conference.ui.BaseFragment;
import cn.doctorpda.conference.ui.CollectionActivity;
import cn.doctorpda.conference.ui.MyMeetingActivity;
import cn.doctorpda.conference.ui.personal.dialog.FeedbackFragment;
import cn.doctorpda.conference.ui.personal.dialog.LoginDialogFragment;
import cn.doctorpda.conference.ui.personal.dialog.PersonalSettingDialogFragment;
import cn.doctorpda.conference.ui.personal.dialog.SystemSettingDialogFragment;
import cn.doctorpda.conference.utils.ImageUtils;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.StringUtils;
import cn.doctorpda.conference.utils.T;
import cn.doctorpda.conference.view.CircleImageView;
import cn.doctorpda.conference.view.barcode.QRActivity;
import cn.doctorpda.conference.view.callbackview.IChangeHeadView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/17.
 */
public class PersonalFragment extends BaseFragment implements View.OnClickListener, IChangeHeadView {

    private ImageView imv_personal_setting;
    private CircleImageView imv_user_head;
    private LinearLayout ll_my_meeting, ll_my_collection, ll_sign_up, ll_feed_back;
    private TextView mUserName;
    private View view;
    private Boolean isFromHeadSetting = false;

    private ChangeHeadPresenter changeHeadPresenter;

    public static PersonalFragment newInstance() {
        PersonalFragment fragment = new PersonalFragment();
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        User user = UserInfo.getUserInfo();
        if (user != null && !isFromHeadSetting) {
            ImageUtils.loadImage(getActivity(), user.getAVATAR(), imv_user_head);
//            T.showShort(getContext(),"复现");
            L.d("复现头像" + user.getAVATAR());
            if (!StringUtils.isEmpty(user.getNAME())) {
                mUserName.setText(user.getNAME());
            } else {
                mUserName.setText(user.getNICKNAME());
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view != null) {
            return view;
        }

        view = inflater.inflate(R.layout.fragment_my_centre_new, container, false);
        initView(view);

        EventBus.getDefault().register(this);
        changeHeadPresenter = new ChangeHeadPresenter(this);
        return view;
    }

    private void initView(View view) {

        ll_feed_back = (LinearLayout) view.findViewById(R.id.ll_feed_back);
        imv_personal_setting = (ImageView) view.findViewById(R.id.imv_personal_setting);
        ll_my_meeting = (LinearLayout) view.findViewById(R.id.ll_my_meeting);
        ll_my_collection = (LinearLayout) view.findViewById(R.id.ll_my_collection);
        ll_sign_up = (LinearLayout) view.findViewById(R.id.ll_sign_up);
        imv_user_head = (CircleImageView) view.findViewById(R.id.imv_user_head);

        view.findViewById(R.id.ll_setting).setOnClickListener(this);

        imv_user_head.setOnClickListener(this);
        imv_personal_setting.setOnClickListener(this);
        ll_my_meeting.setOnClickListener(this);
        ll_my_collection.setOnClickListener(this);
        ll_sign_up.setOnClickListener(this);
        ll_feed_back.setOnClickListener(this);
        mUserName = (TextView) view.findViewById(R.id.tv_user_name);
        mUserName.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (UserInfo.getUserInfo() == null) {
            LoginDialogFragment cacheDialogFragment = new LoginDialogFragment();
            cacheDialogFragment.show(getActivity().getSupportFragmentManager(), null);
            cacheDialogFragment.setOnLoginListener(new LoginDialogFragment.OnLoginListener() {
                @Override
                public void setLoginListener(Msg msg, User user) {
//                    T.showShort(getActivity(), msg.getMsg());
                    if (msg.isSuccess()) {
                        if (user.getAVATAR() != null) {
                            ImageUtils.loadImage(getActivity(), user.getAVATAR(), imv_user_head);
                        }
                        if (!StringUtils.isEmpty(user.getNAME())) {
                            mUserName.setText(user.getNAME());
                        } else {
                            mUserName.setText(user.getNICKNAME());
                        }
                    }
                }
            });
            return;
        }
        switch (v.getId()) {
            case R.id.imv_personal_setting:
                if (UserInfo.getUserInfo() != null) {
                    PersonalSettingDialogFragment pDialogFragment = new PersonalSettingDialogFragment();
                    pDialogFragment.show(getActivity().getSupportFragmentManager(), null);
                    pDialogFragment.setLogoutListener(new PersonalSettingDialogFragment.OnLogoutListener() {
                                                          @Override
                                                          public void setLogoutListener(Msg msg) {
                                                              if (msg.isSuccess()) {
                                                                  UserInfo.clearUser();
                                                                  ClientInfo.setAccessEmpty(getActivity());
                                                                  mUserName.setText("登录");
                                                                  ImageUtils.loadImage(getActivity(), R.drawable.icon_wode_normal, imv_user_head);
//                                                              imv_user_head.setBackgroundResource( R.drawable.icon_wode_normal);
                                                              }

                                                          }
                                                      }

                    );
                }
                break;
            case R.id.ll_my_meeting:
                Intent toMymMeeting = new Intent();
                toMymMeeting.setClass(getActivity(), MyMeetingActivity.class);
                startActivity(toMymMeeting);
                break;
            case R.id.ll_my_collection:
                Intent toCollection = new Intent();
                toCollection.setClass(getActivity(), CollectionActivity.class);
                startActivity(toCollection);
                break;
            case R.id.ll_sign_up:
                Intent i = new Intent();
                i.setClass(getActivity(), QRActivity.class);
                startActivity(i);
                break;
            case R.id.ll_feed_back:
                FeedbackFragment feedbackFragment = new FeedbackFragment();
                feedbackFragment.show(getActivity().getSupportFragmentManager(), null);
                break;

            case R.id.ll_setting:
                if (UserInfo.getUserInfo() != null) {
                    SystemSettingDialogFragment systemSettingDialogFragment = new SystemSettingDialogFragment();
                    systemSettingDialogFragment.show(getActivity().getSupportFragmentManager(), null);
                    systemSettingDialogFragment.setLogout2Listener(new SystemSettingDialogFragment.OnLogout2Listener() {
                        @Override
                        public void setLogout2Listener(Msg msg) {
                            if (msg.isSuccess()) {
                                UserInfo.clearUser();
                                ClientInfo.setAccessEmpty(getActivity());
                                mUserName.setText("登录");
                                ImageUtils.loadImage(getActivity(), R.drawable.icon_wode_normal, imv_user_head);
//                                                              imv_user_head.setBackgroundResource( R.drawable.icon_wode_normal);
                            }
                        }
                    });
                }
                break;

        }
    }

    @Override
    public String getPageName() {
        return "PersonalFragment";
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginMessageEvent(GetLoginMessage messageEvent) {
        if (messageEvent.getMessage().equals("FromVerifyCodeLogin")) {
            User user = UserInfo.getUserInfo();
            ImageUtils.loadImage(getActivity(), user.getAVATAR(), imv_user_head);
            if (!StringUtils.isEmpty(user.getNAME())) {
                mUserName.setText(user.getNAME());
            } else {
                mUserName.setText(user.getNICKNAME());
            }
        } else {//过滤主页乘客，重写方法
            mUserName.setText(messageEvent.getMessage());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowHeadEvent(GetBitmap messageEvent) {

        User user = UserInfo.getUserInfo();
        if (messageEvent != null) {
            isFromHeadSetting = true;
            changeHeadPresenter.getChangeHeadData(user.getMOBILE(), "avatar", System.currentTimeMillis() + ".jpg", messageEvent.getFile());

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIsNew(IsNew isNewVersion) {
        if (isNewVersion.getMsg().equals("isNew")) {
            T.showShort(getContext(), "亲，已是最新版本！");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        isFromHeadSetting = false;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setNewHeadView(Msg msg, UserIcon user) {
//        T.showShort(getContext(), "头像"+msg.getMsg());
        if (msg.isSuccess()) {
            isFromHeadSetting = true;
            User user_l = UserInfo.getUserInfo();
            if (user_l != null) {
                user_l.setAVATAR(user.getAVATAR());
                UserInfo.saveUserInfo(user_l);
                L.d("保存新头像" + user_l.getAVATAR());
            }
            ImageUtils.loadImage(getActivity(), user_l.getAVATAR() + "?imageView2/2/w/180/h/180", imv_user_head);

            T.showShort(getContext(), "头像修改成功");
        } else {

        }
    }

    @Override
    public void setNewResult(Msg msg) {
        if (!msg.getStatus().equals("success")) {
            T.showShort(getContext(), msg.getMsg());
            T.showShort(getContext(), "来自这热" + msg.getMsg());
        }
    }

    @Override
    public void setNewHeadError(Call call, Exception e) {
//        isFromHeadSetting = true;
        T.showShort(getContext(), "设置失败，请稍后再试");
    }
}
